package com.octopus.kernal.util.generate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.octopus.kernal.util.xml.*;

public class JspCodeGenerator {
	
	private static Log log = LogFactory.getLog(JspCodeGenerator.class);
	
	@SuppressWarnings("unused")
	private BusinessModel businessModel;
	
	private String templatePath;
	
	private String outputPath;
		
	public JspCodeGenerator(String basePath, BusinessModel businessModel){
		this.businessModel = businessModel;
		this.templatePath = basePath + "/src/main/webapp/WEB-INF/page/template/";
		this.outputPath = basePath + "/src/main/webapp/WEB-INF/page/generated/";
	}
	
	public void generateQueryPage(Entity entity) throws Exception{
		this.generatePage(entity, "query.jsp");
	}
	
	public void generateEditPage(Entity entity) throws Exception{
		this.generatePage(entity, "edit.jsp");
	}
	
	private void generatePage(Entity entity, String fileName) throws Exception{
		String template = this.templatePath + fileName;
		String folder = this.outputPath + "/" + entity.getAlias();
		String jsp = folder + "/" + fileName;
		File file = new File(folder);
		if(!file.exists())
			file.mkdir();
		file = new File(jsp);
		if(!file.exists())
			file.createNewFile();
		FileReader fr = new FileReader(template);
		BufferedReader reader = new BufferedReader(fr); 
		FileWriter writer = new FileWriter(jsp);
		String line;
		try{
	        while((line = reader.readLine()) != null) { 
	        	line = line.replaceAll("<entity:alias/>", entity.getAlias());
	        	line = line.replaceAll("<entity:name/>", entity.getName());
	        	line = line.replaceAll("<entity:model/>", StringUtils.uncapitalize(entity.getName()) + "Struct");
	        	line = line.replaceAll("<entity:search/>", "search" + entity.getName() + "Command");
	        	writer.write(line); 
	        	writer.write(System.getProperty("line.separator"));
	        }
		}catch(Exception e){
			log.equals("Generate page error:" + this.outputPath + "/" + entity.getAlias() + "/" + fileName);
			throw e;
		}finally{
	        reader.close(); 
	        writer.close(); 
		}
	}

}
